package com.example.zcq.rxjava2retrofitmvp.activity;

import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.example.zcq.rxjava2retrofitmvp.R;
import com.example.zcq.rxjava2retrofitmvp.base.BaseActivity;
import com.example.zcq.rxjava2retrofitmvp.constant.Constant;

import java.util.ArrayList;
import java.util.List;


/**
 * @author zcq
 * @package com.example.zcq.rxjava2retrofitmvp.activity
 * @fileName SeeContactsActivity
 * @description: 描述
 * @date 2018/9/27 10:39
 * @org zcq有限公司
 * @email 1015857694@qq.com
 */

public class SeeContactsActivity extends BaseActivity {


    private ListView mLv;
    private List<String> mArrayList = new ArrayList<>();

    private ArrayAdapter<String> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_see_contacts);

        initView();

        readContacts();

    }

    private void readContacts() {
        //查看是否有权限
        if (hasPermission(Constant.READ_CONTACTS_PERMISSION)) {
            Cursor cursor = null;
            try {
                //查询联系人数据
                cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
                if (cursor != null) {
                    while (cursor.moveToNext()) {
                        //获取联系人姓名
                        String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        //获取电话号码
                        String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        mArrayList.add(displayName + "\n" + number);
                    }
                    adapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //关闭游标
                if (cursor != null) {
                    cursor.close();
                }
            }


        } else {
            requestPermission(Constant.READ_CONTACTS_CODE, Constant.READ_CONTACTS_PERMISSION);
        }
    }


    private void initView() {
        mLv = (ListView) findViewById(R.id.lv);
        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mArrayList);
        mLv.setAdapter(adapter);
    }

    //获取查看通讯录权限以后干的事

    @Override
    public void seeContacts() {
        readContacts();
    }
}
